package com.feng.demo.thread;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 并行加载监控
 * 
 * @author Administrator
 */
public class TestThreadPool {
	private static int produceTaskSleepTime = 5;
	private static int produceTaskMaxNumber = 1000;
	private static int corePoolSize = 1;
	private static int maximumPoolSize = 2;
	private static long keepAliveTime = 5;

	public static void main(String[] args) {
		// 构造一个线程池
		// 创建一个带有给定的（固定）容量和默认访问策略的 ArrayBlockingQueue。一个由数组支持的有界阻塞队列。此队列按
		// FIFO（先进先出）原则对元素进行排序。队列的头部 是在队列中存在时间最长的元素。队列的尾部
		// 是在队列中存在时间最短的元素。新元素插入到队列的尾部，队列检索操作则是从队列头部开始获得元素。
		//ThreadPoolExecutor threadPool = new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(100),new ThreadPoolExecutor.DiscardOldestPolicy());
		// 创建一个带有给定的（固定）容量和默认访问策略的 ArrayBlockingQueue。
		ThreadPoolExecutor threadPool = new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(100),new ThreadPoolExecutor.DiscardOldestPolicy());
		for (int i = 1; i <= produceTaskMaxNumber; i++) {
			try {
				// 产生一个任务，并将其加入到线程池
				String task = "task@ " + i;
				System.out.println("put " +Thread.currentThread().getName()+ task);

				// 便于观察，等待一段时间
				Thread.sleep(produceTaskSleepTime);
				threadPool.execute(new ThreadPoolTask(task));
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
}
